package com.polaris.live.ui.live.widget

import android.animation.LayoutTransition
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.polaris.live.common.util.removeIfBy24
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import com.polaris.live.widget.drag.OnViewDestroyListener
import java.util.LinkedList

/**
 * LiveAnswerView
 *
 * @author Created by lucas on 2023/11/11 13:34
 */
class LiveAnswerView(context: Context, attributeSet: AttributeSet) :
    LinearLayout(context, attributeSet),
    OnViewDestroyListener, OnLiveAnswerListener {

    private val mAnswerQueue = LinkedList<CallSignalingMessage>()
    private val mCurrentViews = ArrayList<LiveAnswerItemView>()

    private var mOnLiveAnswerListener: OnLiveAnswerListener? = null

    init {
        orientation = VERTICAL

        this.layoutTransition = LayoutTransition().apply {
            setAnimateParentHierarchy(false)
            disableTransitionType(LayoutTransition.APPEARING)
            disableTransitionType(LayoutTransition.DISAPPEARING)
            disableTransitionType(LayoutTransition.CHANGE_APPEARING)
            setDuration(LayoutTransition.CHANGE_DISAPPEARING, 350)
        }
    }

    /**
     * 来电
     */
    fun onLivingToCall(callBean: CallSignalingMessage) {
        if (mCurrentViews.size >= 2) {
            mAnswerQueue.add(callBean)
            return
        }
        showItem(callBean)
    }

    /**
     * 取消来电
     */
    fun onCancelToCall(callBean: CallSignalingMessage) {
        mAnswerQueue.removeIfBy24 {
            it.callId == callBean.callId
        }
        mCurrentViews.forEach {
            it.closeWindowIfEnd(callBean.callId)
        }
    }

    override fun onViewDestroy(view: View) {
        mCurrentViews.remove(view)
        mAnswerQueue.poll()?.also {
            showItem(it)
        }
    }

    private fun showItem(callBean: CallSignalingMessage) {
        LiveAnswerItemView(context).apply {
            mCurrentViews.add(this)
            setOnLiveAnswerListener(this@LiveAnswerView)
            setOnViewDestroyListener(this@LiveAnswerView)
            onLivingToCall(this@LiveAnswerView, callBean)
        }
    }

    override fun onAnswer(message: CallSignalingMessage, needLoading: Boolean) {
        mOnLiveAnswerListener?.onAnswer(message, needLoading)
    }

    override fun onRefuse(message: CallSignalingMessage, type: Int) {
        mOnLiveAnswerListener?.onRefuse(message, type)
    }

    fun setOnLiveAnswerListener(l: OnLiveAnswerListener) {
        mOnLiveAnswerListener = l
    }
}